<template>
  <div class="upload-page">
    <NavBar />
    
    <a-layout-content class="content">
      <div class="upload-container">
        <div class="header">
          <h1 class="title">
            <database-outlined /> {{ $t('nav.upload') }}
          </h1>
          <p class="subtitle">{{ $t('upload.subtitle', '上传CSV文件以更新或追加蛋白质数据') }}</p>
        </div>

        <!-- 上传配置区域 -->
        <a-card class="config-card" :title="$t('upload.config', '导入配置')" :bordered="false">
          <!-- 模式选择 -->
          <div class="config-item">
            <label class="config-label">
              <thunderbolt-outlined /> {{ $t('upload.importMode', '导入模式') }}
            </label>
            <a-radio-group v-model:value="importMode" button-style="solid" size="large">
              <a-radio-button value="append">
                <plus-outlined /> {{ $t('upload.modeAppend', '追加数据') }}
              </a-radio-button>
              <a-radio-button value="replace">
                <swap-outlined /> {{ $t('upload.modeReplace', '覆盖数据') }}
              </a-radio-button>
            </a-radio-group>
            <div class="mode-description">
              <info-circle-outlined style="color: #1890ff; margin-right: 4px;" />
              <span v-if="importMode === 'append'">
                {{ $t('upload.appendDesc', '将新数据添加到现有数据库中，保留原有数据') }}
              </span>
              <span v-else style="color: #ff4d4f;">
                {{ $t('upload.replaceDesc', '⚠️ 警告：将清空现有所有数据，然后导入新数据') }}
              </span>
            </div>
          </div>

          <!-- 文件上传 -->
          <div class="config-item">
            <label class="config-label">
              <file-outlined /> {{ $t('upload.selectFile', '选择文件') }}
            </label>
            <a-upload-dragger
              v-model:fileList="fileList"
              name="file"
              :multiple="false"
              :before-upload="beforeUpload"
              accept=".csv"
              :showUploadList="false"
              @change="handleChange"
            >
              <p class="ant-upload-drag-icon">
                <inbox-outlined :style="{ fontSize: '48px', color: '#1890ff' }" />
              </p>
              <p class="ant-upload-text">
                {{ $t('upload.dragText', '点击或拖拽 CSV 文件到此区域上传') }}
              </p>
              <p class="ant-upload-hint">
                {{ $t('upload.sizeLimit', `支持单个文件上传，大小不超过 ${maxUploadSize}MB`) }}
              </p>
            </a-upload-dragger>

            <!-- 已选文件 -->
            <div v-if="selectedFile" class="selected-file">
              <file-text-outlined style="color: #52c41a; font-size: 20px;" />
              <span class="file-name">{{ selectedFile.name }}</span>
              <span class="file-size">({{ formatFileSize(selectedFile.size) }})</span>
              <a-button type="link" danger @click="removeFile">
                <delete-outlined /> {{ $t('common.remove', '移除') }}
              </a-button>
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <a-button 
              type="primary" 
              size="large" 
              :loading="uploading" 
              :disabled="!selectedFile"
              @click="handleUpload"
            >
              <upload-outlined v-if="!uploading" />
              {{ uploading ? $t('upload.uploading', '导入中...') : $t('upload.startImport', '开始导入') }}
            </a-button>
            <a-button size="large" @click="clearAll" :disabled="uploading">
              <clear-outlined /> {{ $t('common.reset', '重置') }}
            </a-button>
          </div>
        </a-card>

        <!-- 终端日志区域 -->
        <a-card 
          class="terminal-card" 
          :title="$t('upload.terminal', '操作日志')" 
          :bordered="false"
          v-if="logs.length > 0"
        >
          <div class="terminal">
            <div 
              v-for="(log, index) in logs" 
              :key="index" 
              :class="['log-entry', `log-${log.level}`]"
            >
              <span class="log-time">{{ formatTime(log.timestamp) }}</span>
              <span class="log-level">{{ getLevelIcon(log.level) }}</span>
              <span class="log-message">{{ log.message }}</span>
            </div>
            <!-- 自动滚动到底部 -->
            <div ref="terminalBottom"></div>
          </div>
        </a-card>

        <!-- 使用说明 -->
        <a-card class="help-card" :title="$t('upload.helpTitle', '使用说明')" :bordered="false">
          <a-alert
            :message="$t('upload.dataStructure', 'CSV 数据结构要求')"
            type="info"
            show-icon
            style="margin-bottom: 16px;"
          >
            <template #description>
              <div class="help-content">
                <p><strong>{{ $t('upload.requiredColumns', '必需列') }}:</strong></p>
                <ul>
                  <li><code>Species</code> - {{ $t('upload.colSpecies', '物种名称') }}</li>
                  <li><code>Assembly</code> - {{ $t('upload.colAssembly', '组装信息') }}</li>
                  <li><code>Accession</code> - {{ $t('upload.colAccession', '登录号（唯一标识）') }}</li>
                  <li><code>The neighbor of</code> - {{ $t('upload.colNeighbor', '邻近基因') }}</li>
                  <li><code>Type</code> - {{ $t('upload.colType', '类型') }}</li>
                  <li><code>Protein sequence</code> - {{ $t('upload.colSequence', '蛋白质序列') }}</li>
                  <li><code>CDS</code> - {{ $t('upload.colCDS', '编码序列') }}</li>
                </ul>
                <p><strong>{{ $t('upload.optionalColumns', '可选列') }}:</strong></p>
                <ul>
                  <li><code>query</code> - {{ $t('upload.colQuery', '用于匹配 PDB 文件（将自动处理）') }}</li>
                </ul>
                <p><strong>{{ $t('upload.excludedColumns', '自动排除列') }}:</strong></p>
                <ul>
                  <li><code>acr_source</code>, <code>query</code> - {{ $t('upload.autoExclude', '这些列将在导入时自动排除') }}</li>
                </ul>
              </div>
            </template>
          </a-alert>
        </a-card>
      </div>
    </a-layout-content>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import config from '../config/env'
import axiosInstance from '../utils/axios'
import NavBar from '../components/NavBar.vue'
import {
  DatabaseOutlined,
  ThunderboltOutlined,
  PlusOutlined,
  SwapOutlined,
  FileOutlined,
  InboxOutlined,
  UploadOutlined,
  ClearOutlined,
  InfoCircleOutlined,
  FileTextOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { useI18n } from 'vue-i18n'

const { t } = useI18n()

// 状态
const fileList = ref([])
const selectedFile = ref(null)
const uploading = ref(false)
const importMode = ref('append')
const logs = ref([])
const terminalBottom = ref(null)
const maxUploadSize = ref(20)

// 获取配置
axios.get(`${config.API_BASE_URL}/config/`).then(response => {
  maxUploadSize.value = response.data.max_upload_size_mb
}).catch(() => {
  maxUploadSize.value = 20
})

// 文件大小格式化
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i]
}

// 时间格式化
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour12: false })
}

// 日志级别图标
const getLevelIcon = (level) => {
  switch (level) {
    case 'error':
      return '❌'
    case 'warning':
      return '⚠️ '
    case 'info':
    default:
      return 'ℹ️ '
  }
}

// 添加日志
const addLog = (message, level = 'info') => {
  logs.value.push({
    timestamp: new Date().toISOString(),
    level,
    message
  })
  // 自动滚动到底部
  nextTick(() => {
    if (terminalBottom.value) {
      terminalBottom.value.scrollIntoView({ behavior: 'smooth' })
    }
  })
}

// 文件变化处理
const handleChange = (info) => {
  const { file } = info
  if (file.status === 'removed') {
    selectedFile.value = null
  }
}

// 上传前验证
const beforeUpload = (file) => {
  const isCSV = file.name.endsWith('.csv')
  if (!isCSV) {
    message.error(t('upload.errorFormat', 'Only CSV files are allowed!'))
    return false
  }
  
  const isLt20M = file.size / 1024 / 1024 < maxUploadSize.value
  if (!isLt20M) {
    message.error(t('upload.errorSize', `File must be smaller than ${maxUploadSize.value}MB!`))
    return false
  }
  
  selectedFile.value = file
  logs.value = [] // 清空之前的日志
  addLog(t('upload.fileSelected', `File selected: ${file.name} (${formatFileSize(file.size)})`))
  return false // 阻止自动上传
}

// 移除文件
const removeFile = () => {
  selectedFile.value = null
  fileList.value = []
  logs.value = []
}

// 清空所有
const clearAll = () => {
  removeFile()
  importMode.value = 'append'
}

// 开始上传
const handleUpload = async () => {
  if (!selectedFile.value) {
    message.warning(t('upload.selectFileFirst', 'Please select a file first!'))
    return
  }

  // 如果是覆盖模式，需要二次确认
  if (importMode.value === 'replace') {
    const confirmed = window.confirm(
      t('upload.confirmReplace', 'Are you sure you want to REPLACE all existing data? This action cannot be undone!')
    )
    if (!confirmed) {
      addLog(t('upload.cancelled', 'Import cancelled by user'), 'warning')
      return
    }
  }

  uploading.value = true
  addLog(t('upload.startUploading', 'Starting upload...'))

  const formData = new FormData()
  formData.append('file', selectedFile.value)
  formData.append('mode', importMode.value)

  try {
    const response = await axiosInstance.post(
      '/upload_csv/', 
      formData,
      {
        headers: { 'Content-Type': 'multipart/form-data' }
      }
    )

    // 显示后端返回的日志
    if (response.data.logs) {
      logs.value = response.data.logs
    }

    if (response.data.success) {
      message.success(t('upload.success', 'Import completed successfully!'))
    } else {
      message.error(response.data.message || t('upload.failed', 'Import failed!'))
    }
  } catch (error) {
    console.error('Upload error:', error)
    
    // 尝试从错误响应中提取日志
    if (error.response && error.response.data && error.response.data.logs) {
      logs.value = error.response.data.logs
    } else {
      addLog(t('upload.errorOccurred', `Error: ${error.message}`), 'error')
    }
    
    const errorMsg = error.response?.data?.message || error.message || t('upload.errorUnknown', 'Unknown error')
    message.error(errorMsg)
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.upload-page {
  min-height: 100vh;
  background: #f5f7fa;
}

.content {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
}

.upload-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.header {
  text-align: center;
  margin-bottom: 8px;
}

.title {
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.subtitle {
  font-size: 16px;
  color: #909399;
  margin: 8px 0 0 0;
}

.config-card, .terminal-card, .help-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
}

.config-card :deep(.ant-card-head),
.terminal-card :deep(.ant-card-head),
.help-card :deep(.ant-card-head) {
  background: white;
  color: #2c3e50;
  border-bottom: 1px solid #e4e7ed;
}

.config-card :deep(.ant-card-head-title),
.terminal-card :deep(.ant-card-head-title),
.help-card :deep(.ant-card-head-title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 18px;
}

.config-item {
  margin-bottom: 24px;
}

.config-item:last-child {
  margin-bottom: 0;
}

.config-label {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 12px;
}

.mode-description {
  margin-top: 12px;
  padding: 12px 16px;
  background: #f0f5ff;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
}

.selected-file {
  margin-top: 16px;
  padding: 16px;
  background: #f0f9ff;
  border: 1px solid #d1e9ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-name {
  flex: 1;
  font-weight: 600;
  color: #2c3e50;
}

.file-size {
  color: #909399;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 24px;
}

:deep(.ant-btn-primary) {
  background: #409eff;
  border-color: #409eff;
}

:deep(.ant-btn-primary:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

:deep(.ant-radio-button-wrapper-checked) {
  background: #409eff;
  border-color: #409eff;
}

:deep(.ant-radio-button-wrapper-checked:hover) {
  background: #66b1ff;
  border-color: #66b1ff;
}

/* 终端样式 */
.terminal {
  background: #1e1e1e;
  border-radius: 4px;
  padding: 16px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  max-height: 400px;
  overflow-y: auto;
  color: #d4d4d4;
}

.log-entry {
  padding: 4px 0;
  display: flex;
  gap: 8px;
  line-height: 1.6;
}

.log-time {
  color: #858585;
  min-width: 80px;
}

.log-level {
  min-width: 24px;
}

.log-message {
  flex: 1;
}

.log-info .log-message {
  color: #d4d4d4;
}

.log-warning .log-message {
  color: #d4a72c;
}

.log-error .log-message {
  color: #f48771;
}

/* 帮助内容 */
.help-content {
  font-size: 14px;
  color: #606266;
}

.help-content ul {
  margin: 8px 0 8px 20px;
}

.help-content li {
  margin: 4px 0;
}

.help-content code {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  color: #409eff;
  border: 1px solid #e4e7ed;
}

.help-content strong {
  color: #2c3e50;
}

.help-content p {
  margin-bottom: 12px;
}

/* 卡片hover效果 */
.config-card:hover, .terminal-card:hover, .help-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

/* 滚动条样式 */
.terminal::-webkit-scrollbar {
  width: 8px;
}

.terminal::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.terminal::-webkit-scrollbar-thumb {
  background: #555;
  border-radius: 4px;
}

.terminal::-webkit-scrollbar-thumb:hover {
  background: #777;
}
</style>